package cn.harry.cabinet.view.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.harry.cabinet.R
import cn.harry.cabinet.model.entity.UsageRecord
import cn.harry.cabinet.model.enums.OperationType
import java.text.SimpleDateFormat
import java.util.*

/**
 * 使用记录列表适配器
 */
class UsageRecordAdapter(
    private val onItemClick: (UsageRecord) -> Unit,
    private val onDeleteClick: (UsageRecord) -> Unit
) : RecyclerView.Adapter<UsageRecordAdapter.ViewHolder>() {

    private var records: List<UsageRecord> = emptyList()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
    private val dateOnlyFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

    @SuppressLint("NotifyDataSetChanged")
    fun setRecords(newRecords: List<UsageRecord>) {
        records = newRecords
        notifyDataSetChanged()
    }
    
    fun getRecords(): List<UsageRecord> = records
    
    fun removeRecord(record: UsageRecord) {
        val position = records.indexOf(record)
        if (position != -1) {
            records = records.toMutableList().apply { removeAt(position) }
            notifyItemRemoved(position)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_usage_record, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(records[position])
    }

    override fun getItemCount(): Int = records.size

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val tvEmployeeId: TextView = itemView.findViewById(R.id.tvEmployeeId)
        private val tvName: TextView = itemView.findViewById(R.id.tvName)
        private val tvCardNumber: TextView = itemView.findViewById(R.id.tvCardNumber)
        private val tvStatus: TextView = itemView.findViewById(R.id.tvStatus)
        private val tvTakeTime: TextView = itemView.findViewById(R.id.tvTakeTime)
        private val tvReturnTime: TextView = itemView.findViewById(R.id.tvReturnTime)
        private val tvDuration: TextView = itemView.findViewById(R.id.tvDuration)
        private val btnDelete: ImageButton = itemView.findViewById(R.id.btnDelete)

        fun bind(record: UsageRecord) {
            // 工号
            tvEmployeeId.text = "工号: ${record.employeeId}"
            
            // 姓名
            tvName.text = record.name
            
            // 卡号
            if (record.cardNumber != null) {
                tvCardNumber.visibility = View.VISIBLE
                tvCardNumber.text = "卡号: ${record.cardNumber}"
            } else {
                tvCardNumber.visibility = View.GONE
            }
            
            // 状态
            val (statusText, statusColor) = when (record.status) {
                OperationType.RETRIEVE -> "取出" to 0xFFFF9800.toInt() // 橙色
                OperationType.STORE -> "归还" to 0xFF4CAF50.toInt() // 绿色
                else -> "未知" to 0xFF757575.toInt() // 灰色
            }
            tvStatus.text = statusText
            tvStatus.setTextColor(statusColor)
            
            // 取出时间
            if (record.takeTime != null) {
                tvTakeTime.visibility = View.VISIBLE
                tvTakeTime.text = "取出: ${dateFormat.format(record.takeTime)}"
            } else {
                tvTakeTime.visibility = View.GONE
            }
            
            // 归还时间
            if (record.returnTime != null) {
                tvReturnTime.visibility = View.VISIBLE
                tvReturnTime.text = "归还: ${dateFormat.format(record.returnTime)}"
            } else {
                tvReturnTime.visibility = View.GONE
            }
            
            // 使用时长
            if (record.takeTime != null && record.returnTime != null) {
                tvDuration.visibility = View.VISIBLE
                val duration = record.returnTime.time - record.takeTime.time
                tvDuration.text = "时长: ${formatDuration(duration)}"
            } else {
                tvDuration.visibility = View.GONE
            }
            
            // 删除按钮
            btnDelete.setOnClickListener {
                onDeleteClick(record)
            }
            
            // 点击事件
            itemView.setOnClickListener {
                onItemClick(record)
            }
        }
        
        /**
         * 格式化时长
         */
        private fun formatDuration(durationMillis: Long): String {
            val seconds = durationMillis / 1000
            val minutes = seconds / 60
            val hours = minutes / 60
            val days = hours / 24
            
            return when {
                days > 0 -> "${days}天${hours % 24}小时"
                hours > 0 -> "${hours}小时${minutes % 60}分钟"
                minutes > 0 -> "${minutes}分钟${seconds % 60}秒"
                else -> "${seconds}秒"
            }
        }
    }
}
